import Component from 'utils/js/jquery-component';
import createClass from 'utils/js/create-class';
import s from './index.css';
import html from './index.html';
import { qqFaces } from 'utils/js/wordsToEmoji';
import platform from 'utils/js/platform';

export default createClass(Component, {
  __name__: 'Example',
  locals: s,

  __init__: function (el) {
    this.$wrap = this.$(el || document.body);
    this.$html = this.$(this.rh(html));
    this.$html.appendTo(this.$wrap);
    this.$send = this.$html.find(this.rs('.send'));
    this.$textarea = this.$html.find(this.rs('.textarea'));
    this.prevWords = ''; // 输入框内容发生改变前的值
    this.$emoji = this.$html.find(this.rs('.emoji'));
    this.$smile = this.$html.find(this.rs('.smile'));
    this.$mask = this.$html.find(this.rs('.mask'));
    this.envents = {};

    // 初始化所有表情符号
    this.$emoji.find(this.rs('.faces')).html(Object.keys(qqFaces).map(function (key) {
      return `<img data-key="${key}" src="${require('asset/qq_face/' + qqFaces[key] + '.png')}">`;
    }).join(''));

    // 保存this
    var me = this;

    // 点击发送按钮
    this.$send.click(function () {
      me.sendMsg();
    });

    // 输入框输入
    this.$textarea.on('input', function () {
      me.inputMsg();
    });

    // 输入框获取焦点
    this.$textarea.on('focus', function () {
      platform.system == 'ios' && me.keepIosInputBoxSeen();
    });

    // 输入框失去焦点
    this.$textarea.on('blur', function () {
      if (platform.system == 'ios') {
        me.releaseIosInputBoxSeen();
        document.scrollingElement.scrollTop = 0; // 处理ios中输入框失去焦点后界面悬空的问题
      }
      if (/^\s*$/.test(this.value)) this.value = '';
    });

    // 点击笑脸表情按钮
    this.$smile.click(function () {
      me.$emoji.add(me.$mask).toggleClass(s.hide);
    });

    // 点击遮罩层
    this.$mask.click(function () {
      me.$emoji.add(me.$mask).addClass(s.hide);
    });

    // 点击输入QQ表情
    this.$emoji.on('click', 'img', function () {
      me.inputQQFace(this.dataset.key);
    });
  },

  on: function (eventName, eventHandler) { // 注册交互事件
    var handlers = this.envents[eventName] = this.envents[eventName] || [];
    handlers.push(eventHandler);
  },

  keepIosInputBoxSeen: function () { // 处理ios中输入框被遮挡的问题
    var me = this;
    var loop = function () {
      if (document.scrollingElement.scrollHeight - window.innerHeight > 10) {
        document.scrollingElement.scrollTop = 400;
        return;
      }
      me.iosTimer = setTimeout(loop, 300);
    };
    loop();
    setTimeout(function () {
      clearTimeout(me.iosTimer);
    }, 3000);
  },

  releaseIosInputBoxSeen: function () {
    clearTimeout(this.iosTimer);
  },

  autoHeight: function () {
    var textarea = this.$textarea[0];
    textarea.style.height = 0;
    textarea.style.height = textarea.scrollHeight + 'px';
  },

  inputQQFace: function (key) {
    var textarea = this.$textarea[0];
    var words = textarea.value + '{' + key + '}';
    if (words > 100) return; // 最多100个字符
    this.prevWords = textarea.value = words;
    this.autoHeight();
  },

  inputMsg: function () {
    var textarea = this.$textarea[0];
    var words = textarea.value;

    if (this.prevWords.length > words.length) { // 如果是按了退格键
      var i = textarea.selectionStart;
      var prefix = words.slice(0, i);
      var suffix = words.slice(i);
      var deleted = this.prevWords.slice(i, -suffix.length || i + 1);
      if (deleted == '}') { // 如果是删除表情符号
        var arr = prefix.split(/{(?=[^{]+$)/);
        if (qqFaces[arr[1]]) {
          textarea.value = arr[0] + suffix;
          i = arr[0].length;
          textarea.selectionStart = textarea.selectionEnd = i;
        }
      }
    }

    this.prevWords = textarea.value;
    this.autoHeight();
  },

  sendMsg: function () {
    var data = {
      words: this.$textarea.val(),
      imgs: [],
    };
    var handlers = this.envents.send || [];
    handlers.forEach(function (handler) {
      handler(data);
    });
    this.$textarea.val('');
    this.autoHeight();
  },
});
